/*
 * @Author: 杭梓桐
 * @Date: 2023-06-12 09:44:31
 * @LastEditors: 杭梓桐
 * @LastEditTime: 2023-06-13 11:08:34
 * @Description:
 */
import React, { ChangeEvent, useState } from 'react';
import { Select } from 'antd';
const { Option } = Select;

const isValidPhoneNumber = (phoneNumber: string) => {
  const reg = /^1\d{10}$/;
  return reg.test(phoneNumber);
};

const PhoneSelect = () => {
  const [selectedItems, setSelectedItems] = useState<string[]>([]);

  const handleInputKeyDown = (
    event: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    if (
      event.target instanceof HTMLInputElement ||
      event.target instanceof HTMLTextAreaElement
    ) {
      const inputElement = event.target as
        | HTMLInputElement
        | HTMLTextAreaElement;

      if (inputElement.value.trim() !== '' && event.key === 'Enter') {
        const value = inputElement.value.trim();

        // 验证输入的内容是否为手机号
        if (isValidPhoneNumber(value)) {
          setSelectedItems([...selectedItems, value]);
        }
      }
    }
  };

  const handleChange = (value: string[]) => {
    setSelectedItems(value.filter(isValidPhoneNumber));
  };

  const handleDeselect = (value: string) => {
    setSelectedItems(selectedItems.filter((item) => item !== value));
  };

  return (
    <Select
      mode="tags"
      onChange={handleChange}
      onSelect={(value, option) => {
        if (!isValidPhoneNumber(value)) {
          setSelectedItems(selectedItems.filter((item) => item !== value));
        }
      }}
      onDeselect={handleDeselect}
      onInputKeyDown={handleInputKeyDown}
      tokenSeparators={[',']}
      value={selectedItems}
      style={{ width: '100%' }}
      placeholder="请输入手机号，按 Enter 添加"
      // open={false}
    ></Select>
  );
};

export default PhoneSelect;
